<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="我们都知道在写代码的时候，只要使用@Transcation，那么Spring就能帮我们完成事务的处理。那么问题来了，  它是如何来帮我们解决的呢？ 还有如今都是分布式系统，如何来实现一个分布式事务呢？  先把结论说出来，分布式事务其实和Spring的事务实现方式有点类似，你只要看了Spring事务的源码对分布式事务的理解也能有个不小的帮助。 从Spring的事务讲起Spring事务的本质就是切面帮">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring事务以及分布式事务">
<meta property="og:url" content="https://guodh.gitee.io/blog/2017/10/12/2017/Spring%E4%BA%8B%E5%8A%A1%E4%BB%A5%E5%8F%8A%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="我们都知道在写代码的时候，只要使用@Transcation，那么Spring就能帮我们完成事务的处理。那么问题来了，  它是如何来帮我们解决的呢？ 还有如今都是分布式系统，如何来实现一个分布式事务呢？  先把结论说出来，分布式事务其实和Spring的事务实现方式有点类似，你只要看了Spring事务的源码对分布式事务的理解也能有个不小的帮助。 从Spring的事务讲起Spring事务的本质就是切面帮">
<meta property="og:locale">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/proxy.jpeg">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/TransactionIntecptor.png">
<meta property="article:published_time" content="2017-10-12T13:23:07.000Z">
<meta property="article:modified_time" content="2017-11-05T06:45:39.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://olwr1lamu.qnssl.com/proxy.jpeg">

<link rel="canonical" href="https://guodh.gitee.io/blog/2017/10/12/2017/Spring%E4%BA%8B%E5%8A%A1%E4%BB%A5%E5%8F%8A%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>Spring事务以及分布式事务 | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2017/10/12/2017/Spring%E4%BA%8B%E5%8A%A1%E4%BB%A5%E5%8F%8A%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring事务以及分布式事务
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2017-10-12 21:23:07" itemprop="dateCreated datePublished" datetime="2017-10-12T21:23:07+08:00">2017-10-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2017-11-05 14:45:39" itemprop="dateModified" datetime="2017-11-05T14:45:39+08:00">2017-11-05</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>我们都知道在写代码的时候，只要使用@Transcation，那么Spring就能帮我们完成事务的处理。那么问题来了，</p>
<ol>
<li>它是如何来帮我们解决的呢？</li>
<li>还有如今都是分布式系统，如何来实现一个分布式事务呢？</li>
</ol>
<p>先把结论说出来，分布式事务其实和Spring的事务实现方式有点类似，你只要看了Spring事务的源码对分布式事务的理解也能有个不小的帮助。</p>
<h2 id="从Spring的事务讲起"><a href="#从Spring的事务讲起" class="headerlink" title="从Spring的事务讲起"></a>从Spring的事务讲起</h2><p>Spring事务的本质就是切面帮你处理Exception，如果有异常就帮你处理。Spring利用AOP的特性，解耦了Service和DB，这种思路在未来写代码过程中可以多多使用。<br><img src="https://olwr1lamu.qnssl.com/proxy.jpeg" width="40%" height="40%" alt="AOP 概念"/></p>
<h3 id="Spring代理实现"><a href="#Spring代理实现" class="headerlink" title="Spring代理实现"></a>Spring代理实现</h3><p>既然是通过切面实现，那么先来看下TransactionInterceptor的UML结构：<br><img src="https://olwr1lamu.qnssl.com/TransactionIntecptor.png" width="70%" height="70%" alt="TransactionInterceptor.java"/></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// TransactionInterceptor.java</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(<span class="keyword">final</span> MethodInvocation invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 从BeanMap中找到需要代理的Bean</span></span><br><span class="line">Class&lt;?&gt; targetClass = (invocation.getThis() != <span class="keyword">null</span> ? AopUtils.getTargetClass(invocation.getThis()) : <span class="keyword">null</span>);</span><br><span class="line"><span class="comment">// 这个才是代理的大头</span></span><br><span class="line"><span class="keyword">return</span> invokeWithinTransaction(invocation.getMethod(), targetClass, </span><br><span class="line">	<span class="keyword">new</span> InvocationCallback() &#123;</span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">public</span> Object <span class="title">proceedWithInvocation</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> invocation.proceed();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>还有个很有意思的点就是，写了一个简单的Callback（看下面），其实是为了调用invacation的proceed()，有意思。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> <span class="class"><span class="keyword">interface</span> <span class="title">InvocationCallback</span> </span>&#123;</span><br><span class="line">	<span class="function">Object <span class="title">proceedWithInvocation</span><span class="params">()</span> <span class="keyword">throws</span> Throwable</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后是实际代理的地方，让我们分两步来看：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">invokeWithinTransaction</span><span class="params">(Method method, Class&lt;?&gt; targetClass, <span class="keyword">final</span> InvocationCallback invocation)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 获得事务配置的一些参数	</span></span><br><span class="line">  <span class="keyword">final</span> TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);</span><br><span class="line">	</span><br><span class="line">  <span class="keyword">final</span> PlatformTransactionManager tm = determineTransactionManager(txAttr);</span><br><span class="line">  <span class="keyword">final</span> String joinpointIdentification = methodIdentification(method, targetClass);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (txAttr == <span class="keyword">null</span> || !(tm <span class="keyword">instanceof</span> CallbackPreferringPlatformTransactionManager)) &#123;</span><br><span class="line"></span><br><span class="line">  **TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);**</span><br><span class="line">		</span><br><span class="line">		<span class="comment">// 部分一：如果传入的是定义好的TransactionManager</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span> &#123;</span><br><span class="line">  **TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);**</span><br><span class="line">	</span><br><span class="line">		<span class="comment">// 部分二：如果传入的是实现自CallbackPreferringPlatformTransactionManager</span></span><br><span class="line">  &#125;				</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在if/else中处理的代码其实类似，只是高版本的Spring提供了回调函数，提供给使用者来处理不同情况下的触发情况。<br>需要关注的是，可以看到两部分中都有一个生成TransactionInfo的操作，而在createTransactionIfNecessary()中，会将事务的所有信息绑定到transactionInfoHolder即线程上。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">bindToThread</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.oldTransactionInfo = transactionInfoHolder.get();</span><br><span class="line">  transactionInfoHolder.set(<span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>（部分一）然后来看下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Object retVal = <span class="keyword">null</span>;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">	<span class="comment">// 调用链路</span></span><br><span class="line">	retVal = invocation.proceedWithInvocation();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">	<span class="comment">// 这里正是处理回滚，并处理txInfo，抛出错误</span></span><br><span class="line">	completeTransactionAfterThrowing(txInfo, ex);</span><br><span class="line">	<span class="keyword">throw</span> ex;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">finally</span> &#123;</span><br><span class="line">	cleanupTransactionInfo(txInfo);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 事务Commit</span></span><br><span class="line">commitTransactionAfterReturning(txInfo);</span><br><span class="line"><span class="keyword">return</span> retVal;</span><br></pre></td></tr></table></figure>
<p>（部分二）详细代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 如果实现了CallbackPreferringPlatformTransactionManager，那么调用者可以自己来组织遇到不同的Exception所做的操作。</span></span><br><span class="line"><span class="comment">// TransactionCallback会出现三种情况：</span></span><br><span class="line"><span class="comment">// 1. RuntimeException 2.ThrowableHolderException 3.ThrowableHolder</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 通过实现CallbackPreferringPlatformTransactionManager的execute来对上面的三种情况来处理</span></span><br><span class="line"><span class="comment">// 千万记住面向接口编程</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr,</span><br><span class="line">	<span class="keyword">new</span> TransactionCallback&lt;Object&gt;() &#123;</span><br><span class="line">		<span class="comment">// 定义好了三种不同情况的返回情况</span></span><br><span class="line">	  <span class="function"><span class="keyword">public</span> Object <span class="title">doInTransaction</span><span class="params">(TransactionStatus status)</span> </span>&#123;</span><br><span class="line">		  TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);</span><br><span class="line">		    </span><br><span class="line">		    <span class="keyword">try</span> &#123;</span><br><span class="line">			  <span class="keyword">return</span> invocation.proceedWithInvocation();</span><br><span class="line">			&#125; <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">			  <span class="keyword">if</span> (txAttr.rollbackOn(ex)) &#123;</span><br><span class="line">			    <span class="comment">// 情况1，2：需要处理的，可能都是回滚的情况</span></span><br><span class="line">			    <span class="keyword">if</span> (ex <span class="keyword">instanceof</span> RuntimeException) &#123;</span><br><span class="line">			      <span class="keyword">throw</span> (RuntimeException) ex;</span><br><span class="line">			    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			    	<span class="keyword">throw</span> <span class="keyword">new</span> ThrowableHolderException(ex);</span><br><span class="line">			    &#125;</span><br><span class="line">			  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				<span class="comment">// 情况3：代表正常情况</span></span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> ThrowableHolder(ex);</span><br><span class="line">			  &#125;</span><br><span class="line">			&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">			  cleanupTransactionInfo(txInfo);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 有可能需要重新抛出，spring为使用者做好了准备</span></span><br><span class="line">  <span class="keyword">if</span> (result <span class="keyword">instanceof</span> ThrowableHolder) &#123;</span><br><span class="line">    <span class="keyword">throw</span> ((ThrowableHolder) result).getThrowable();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">catch</span> (ThrowableHolderException ex) &#123;</span><br><span class="line">	<span class="keyword">throw</span> ex.getCause();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Spring真正回滚实现"><a href="#Spring真正回滚实现" class="headerlink" title="Spring真正回滚实现"></a>Spring真正回滚实现</h3><p>看了这么多，这下终于要到真正实现回滚的地方啦。也就是部分一中，catch的代码实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">processRollback</span><span class="params">(DefaultTransactionStatus status)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		triggerBeforeCompletion(status);</span><br><span class="line">		<span class="keyword">if</span> (status.hasSavepoint()) &#123;</span><br><span class="line">			status.rollbackToHeldSavepoint();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (status.isNewTransaction()) &#123;</span><br><span class="line">			doRollback(status);</span><br><span class="line">		&#125;</span><br><span class="line">	<span class="comment">// …………省略一堆代码</span></span><br><span class="line">	<span class="keyword">catch</span>()&#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最主要的就是上面两种情况，<br>情况一：是有savePoint的<br>情况二：是没有savePoint的<br>需要说明的是，SAVEPOINT：数据库中在事务内部创建一系列可以 ROLLBACK 的还原点。<br>说道savePoint就必须提到Spring支持的事务传播级别：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>概念</th>
</tr>
</thead>
<tbody><tr>
<td>PROPAGATION_REQUIRED</td>
<td>支持当前事务</td>
</tr>
<tr>
<td>PROPAGATION_NESTED</td>
<td>嵌套事务</td>
</tr>
<tr>
<td>……</td>
<td>……</td>
</tr>
</tbody></table>
<p>这两个的区别就是savePoint的区别，如果是PROPAGATION_REQUIRED，则被嵌套的事务失败，那么所有的事务都会失败。而如果是PROPAGATION_NESTED，会回滚到savePoint。</p>
<p>继续来看代码内容：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rollbackToHeldSavepoint</span><span class="params">()</span> <span class="keyword">throws</span> TransactionException </span>&#123;</span><br><span class="line">	getSavepointManager().rollbackToSavepoint(getSavepoint());</span><br><span class="line">	getSavepointManager().releaseSavepoint(getSavepoint());</span><br><span class="line">	setSavepoint(<span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rollbackToSavepoint</span><span class="params">(Object savepoint)</span> <span class="keyword">throws</span> TransactionException </span>&#123;</span><br><span class="line">	ConnectionHolder conHolder = getConnectionHolderForSavepoint();</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		conHolder.getConnection().rollback((Savepoint) savepoint);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Throwable ex) &#123;...&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="TCC-Transcation-和-2PC-Transcation-与Spring-事务回滚的异曲同工之处"><a href="#TCC-Transcation-和-2PC-Transcation-与Spring-事务回滚的异曲同工之处" class="headerlink" title="TCC-Transcation 和 2PC-Transcation 与Spring 事务回滚的异曲同工之处"></a>TCC-Transcation 和 2PC-Transcation 与Spring 事务回滚的异曲同工之处</h2><p>针对分布式事务，笔者看了两种解决方案：</p>
<blockquote>
<p>TCC-Transcation: <a href="https://github.com/changmingxie/tcc-transaction">https://github.com/changmingxie/tcc-transaction</a><br>2PC-Transcation: <a href="https://github.com/yu199195/happylifeplat-transaction/">https://github.com/yu199195/happylifeplat-transaction/</a></p>
</blockquote>
<p>发现其实都是类似的方案，通过记录各个阶段的状态，来保证事务的完整性。分布式事务提出了一个TranscationManager的概念，所有的事务状态都是TranscationManager来进行持久化，即使发生了事务中断，恢复之后也能通过TranscationManager来回滚。</p>
<p>而如果是调用不同的Service直接返回Exception了，就比较好解决。通过catch Exception，并且通过记录原始值来恢复。</p>
<p>粗略的来看下，先是</p>
<h3 id="2PC-Transcation："><a href="#2PC-Transcation：" class="headerlink" title="2PC-Transcation："></a>2PC-Transcation：</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@TxTransaction</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">testStockFail</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    orderService.save(order)；</span><br><span class="line"> <span class="comment">// 假设这里失败了</span></span><br><span class="line">    stockService.fail(stock);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;stock_fail&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@TxTransaction</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">fail</span><span class="params">(Stock stock)</span> </span>&#123;</span><br><span class="line">    stockMapper.save(<span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里的每个Service都有@TxTransaction注解。每一次调用，都将会在TranscationManager中注册，如果发生了失败，则通过db的Canal去处理所有的事务。</p>
<p>再来看下</p>
<h3 id="TCC-Transcation："><a href="#TCC-Transcation：" class="headerlink" title="TCC-Transcation："></a>TCC-Transcation：</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Compensable(confirmMethod = &quot;confirmRecord&quot;, cancelMethod = &quot;cancelRecord&quot;, transactionContextEditor = MethodTransactionContextEditor.class)</span></span><br><span class="line"><span class="meta">@Transactional</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">record</span><span class="params">(TransactionContext transactionContext, CapitalTradeOrderDto tradeOrderDto)</span> </span>&#123;    </span><br><span class="line">……</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Transactional</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">confirmRecord</span><span class="params">(TransactionContext transactionContext, CapitalTradeOrderDto tradeOrderDto)</span> </span>&#123;    </span><br><span class="line">……    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Transactional</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">cancelRecord</span><span class="params">(TransactionContext transactionContext, CapitalTradeOrderDto tradeOrderDto)</span> </span>&#123;</span><br><span class="line"> ……    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>TCC从代码上来比较清楚，通过切面来处理不同情况下调用什么方法。</p>
<p>其实是不是和Spring事务中的try、catch、finally很像？</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>见微知著，推荐大家可以从小的地方开始，从Spring的事务来分析分布式事务，收获是大大滴。(^o^)/~</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E6%8A%80%E6%9C%AF/" rel="tag"># 技术</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2017/10/03/2017/Paxos%E7%AE%97%E6%B3%95/" rel="prev" title="Paxos算法">
      <i class="fa fa-chevron-left"></i> Paxos算法
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2017/11/26/2018/%E7%BA%BF%E7%A8%8B%E7%9F%A5%E8%AF%86%E6%A2%B3%E7%90%86/" rel="next" title="线程知识梳理">
      线程知识梳理 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%8ESpring%E7%9A%84%E4%BA%8B%E5%8A%A1%E8%AE%B2%E8%B5%B7"><span class="nav-number">1.</span> <span class="nav-text">从Spring的事务讲起</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Spring%E4%BB%A3%E7%90%86%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.1.</span> <span class="nav-text">Spring代理实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Spring%E7%9C%9F%E6%AD%A3%E5%9B%9E%E6%BB%9A%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.2.</span> <span class="nav-text">Spring真正回滚实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TCC-Transcation-%E5%92%8C-2PC-Transcation-%E4%B8%8ESpring-%E4%BA%8B%E5%8A%A1%E5%9B%9E%E6%BB%9A%E7%9A%84%E5%BC%82%E6%9B%B2%E5%90%8C%E5%B7%A5%E4%B9%8B%E5%A4%84"><span class="nav-number">2.</span> <span class="nav-text">TCC-Transcation 和 2PC-Transcation 与Spring 事务回滚的异曲同工之处</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2PC-Transcation%EF%BC%9A"><span class="nav-number">2.1.</span> <span class="nav-text">2PC-Transcation：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TCC-Transcation%EF%BC%9A"><span class="nav-number">2.2.</span> <span class="nav-text">TCC-Transcation：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
